package ks.client.gui.admin.user.listeners;

import javax.swing.JFrame;
import javax.swing.JTextField;
import ks.client.gui.ErrorMessageGUI;
import ks.client.gui.admin.user.UserAdminGUI;

/**
 * Adds a user to the UserModel.
 * The user added can have just a username, or a username and password.
 * Used to update the two tables in the UserAdminGUI.
 * 
 * @author Jennifer Hunt
 *
 */
public class AddUserController {
	/** GUI being managed. */
	UserAdminGUI gui;
	
	/**
	 * Constructor for AddUserController.
	 * 
	 * @param gui
	 */
	public AddUserController(UserAdminGUI gui) {
		this.gui = gui;
	}

	/**
	 * 
	 * Adds a user to the UserModel given a username and password.
	 * Produces an error message if either the username or password fields are empty. 
	 * 
	 * @param name
	 * @param pass
	 */
	public void add(JTextField name, JTextField  pass) {
		if(name.getText().isEmpty() || pass.getText().isEmpty()){
			JFrame pma = new ErrorMessageGUI("Please type a username and password.");
			pma.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			pma.setTitle("Error");
			pma.setVisible(true);
		}
		else{
			
			TempUser u = new TempUser(name.getText(), pass.getText());

			// update the underlying model.
			UserModel model = gui.getModel();
			model.add(u);
		
			//clear the username and passwords fields
			name.setText("");
			pass.setText("");
		
			// make change visible.
			gui.refreshTable();
			}
	}
	
	/**
	 * 
	 * Adds a user to the UserModel given a username.
	 * Produces an error message if the username is blank.
	 * 
	 * @param name
	 */
	public void add(JTextField name) {
		if(name.getText().isEmpty()){
			JFrame pma = new ErrorMessageGUI("Please type a username.");
			pma.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			pma.setTitle("Error");
			pma.setVisible(true);
		}
		else{
			
			TempUser u = new TempUser(name.getText());

			//update the underlying model.
			UserModel model = gui.getModel2();
			model.add(u);
		
			//clear the user name field
			name.setText("");
		
			// make change visible.
			gui.refreshTable();
		}
	}

}
